package com.ziqi.hututubackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ziqi.hututubackend.api.aliyunai.AliYunAiApi;
import com.ziqi.hututubackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.ziqi.hututubackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ziqi.hututubackend.exception.BusinessException;
import com.ziqi.hututubackend.exception.ErrorCode;
import com.ziqi.hututubackend.exception.ThrowUtils;
import com.ziqi.hututubackend.manager.CosManager;
import com.ziqi.hututubackend.manager.upload.FilePictureUpload;
import com.ziqi.hututubackend.manager.upload.PictureUploadTemplate;
import com.ziqi.hututubackend.manager.upload.UrlPictureUpload;
import com.ziqi.hututubackend.model.VO.PictureVO;
import com.ziqi.hututubackend.model.VO.UserVO;
import com.ziqi.hututubackend.model.dto.file.UploadPictureResult;
import com.ziqi.hututubackend.model.dto.picture.*;
import com.ziqi.hututubackend.model.entity.Picture;
import com.ziqi.hututubackend.model.entity.Space;
import com.ziqi.hututubackend.model.entity.User;
import com.ziqi.hututubackend.model.enums.PictureReviewStatusEnum;
import com.ziqi.hututubackend.service.PictureService;
import com.ziqi.hututubackend.mapper.PictureMapper;
import com.ziqi.hututubackend.service.SpaceService;
import com.ziqi.hututubackend.service.UserService;
import com.ziqi.hututubackend.utils.ColorSimilarUtils;
import com.ziqi.hututubackend.utils.ColorTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wang
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-01-11 23:39:47
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private UserService userService;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private CosManager cosManager;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 判断可用性
        ThrowUtils.throwIf(inputSource == null, ErrorCode.PARAMS_ERROR, "图片为空");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        /** 判断当前用户空间是否存在 */
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            //如果存在，数据库查找对应的空间
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "用户空间不存在");
//            //必须空间创建者才能上传图片
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有该空间权限");
//            }
            // 校验空间额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间容量不足");
            }
        }

        // 1、判断是新增还是更新照片
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        //如果为更新照片，校验照片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
//            // 仅本人或管理员可更新|编辑
//            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限编辑");
//            }
            /** 校验空间是否与原来一致 */
            if (spaceId == null) {
                // 如果没有传spaceId，复用原来图片的
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传入的spaceId必须和原来一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间id与原来不一致");
                }
            }
            // cos云存储删除旧图片
            clearPictureFile(oldPicture);
        }

        //2、上传图片，获取图片信息
        // 按用户id划分目录 或 空间划分
        String uploadPathPrefix;
        // 空间id不存在则为公共图库，否则为私有空间
        if (spaceId == null) {
            uploadPathPrefix = String.format("public/%s", loginUser.getId()); // 将图片放在新的文件夹便于管理
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);  //图片放在个人空间里
        }

        // 根据inputsource类型来区分url或本地上传,先默认设置为本地上传
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        // 如果是字符串类型，则为url上传
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }

        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 构造需要入库的图片信息对象
        Picture picture = new Picture();
        picture.setSpaceId(spaceId); //设置空间id
        picture.setUrl(uploadPictureResult.getUrl()); // 设置url
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl()); // 设置缩略图url
        picture.setBaseUrl(uploadPictureResult.getBaseUrl());  //设置原图url
        //  支持图片外层传递图片
        String picName = uploadPictureResult.getPicName();  //设置图片名
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName); // 赋值图片名

        picture.setPicSize(uploadPictureResult.getPicSize()); // 赋值图片尺寸
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());  //上传该图片的用户id
        // 设置图片的主色调
//        picture.setPicColor(uploadPictureResult.getPicColor());
        picture.setPicColor(ColorTransformUtils.getStandardColor(uploadPictureResult.getPicColor()));
        // 设置图片分类和标签
        picture.setCategory(pictureUploadRequest.getCategory());
        picture.setTags(pictureUploadRequest.getTags());

        //3、 如果pictureId不空，表示更新图片，否则新增
        if (pictureId != null) {
            // 更新图片，则添加图片id和更新编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 填充默认审核参数
        fillReviewParams(picture, loginUser);

        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            // mybatisplus提供的方法兼容更新和创建操作
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败，数据库操作失败");
            //只有私有空间存在才更新额度，公共空间不用判断
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        return PictureVO.objToVo(picture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        // 创建新查询对象接收返回参数
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) return queryWrapper; // 如果无查询请求返回null

        //从对象中取所有的值。
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Long spaceId = pictureQueryRequest.getSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();


        //根据搜索词搜索符合条件的数据
        if (StrUtil.isNotBlank(searchText)) {
            // 符合包含图片名或者简介的数据
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText));
        }
        // 根据获取到的数据在数据库中查询，如果空则不查询
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.like(ObjUtil.isNotEmpty(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        //时间 >= 开始编辑时间
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        //时间 < 开始编辑时间
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

        // 对于标签tag抽出每个标签进行查询; 所有标签组合在一起得出的结果
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        // 获取分页列表
        List<Picture> pictureList = picturePage.getRecords();
        // 获取分页数据
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }

        // 对象列表转为封装对象列表VO
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1、关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));

        // 2、填充信息
        // foreach方法遍历list中每个VO对象
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();  // 获取每个图片对应的用户id
            User user = null; // 创建用户对象接收匹配的用户
            // 如果图片对应的用户id存在于List中，提取用户（同一用户只需提取一次）
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            // 用户信息填充到VO对象（代表是这个用户上传的图片）
            pictureVO.setUser(userService.getUserVO(user));
        });
        // 设置分页查询结果，并返回
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }


    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 将传入的picture原始对象转为封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        // 如果图片对应的用户id存在则将它关联到封装类中 (脱敏后的用户信息关联到图片）
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    @Override
    public void vaildPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象取值,校验什么把什么提取出来
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        //id不能为空
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "id不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url过长(不能大于1024)");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 1 取出图片id和对应的审核结果
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        // 审核状态数字对应到汉字
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        //判断是否存在，状态不能是待审核
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2 数据库中查看是否有图片
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "找不到图片");
        // 设置状态和当前状态重复
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "已是该状态,请勿重复审核");
        }
        //调用数据库更新状态
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(oldPicture, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        updatePicture.setReviewStatus(reviewStatus);
        updatePicture.setReviewMessage(pictureReviewRequest.getReviewMessage());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        // 如果是管理员则自动过审
        if (userService.isAdmin(loginUser)) {
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
        } else {
            // 不是管理员则默认设置为待审核状态
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }


    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        //1. 获取搜索词和请求数量，约束请求数量
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix(); //获取设置的图片名称前缀
        // 获取设置的类别和标签
        String category = pictureUploadByBatchRequest.getCategory();
        String tags = JSONUtil.toJsonStr(pictureUploadByBatchRequest.getTags());
        // 如果没有设置图片名称，则使用搜索词
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "一次最多请求30条数据");

        //设置抓取地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        //2. 使用jsoup解析地址的html文档
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        //   获取包含图片的页面主体
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面元素失败");
        }
        // 选择器获取每个元素
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;  // 上传成功的图片个数
        // 遍历图片元素的src属性（即url）
        for (Element imgElemet : imgElementList) {
            String fileUrl = imgElemet.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                //如果找不到链接，则执行下一条
                log.info("当前连接为空，已跳过：{}", fileUrl);
                continue;
            }
            //去掉多余部分参数
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            /** 3. 上传图片 */
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            // 设置图片名称为“名称+序号”
            if (StrUtil.isNotBlank(namePrefix)) {
                pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            }
            // 赋值类别和目录
            pictureUploadRequest.setCategory(category);
            pictureUploadRequest.setTags(tags);
            try {
                // 通过上传图片方法上传
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功， id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            // 获取的数量达到要求时停止
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 将传入的edit类转为picture类
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 将前端传来的json格式tag转为string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 有一些对象edit没有，所以转为picture对象，需要单独赋值; 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        vaildPicture(picture);
        // 判读图片是否存在，才可以进行编辑操作
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 权限校验
//        checkPictureAuth(loginUser, oldPicture);
        // 填充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库编辑
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);

        //判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "找不到要删除的图片");
        //校验图片操作权限
//        checkPictureAuth(loginUser, oldPicture);
        transactionTemplate.execute(status -> {
            // 如果上述都ok，操作数据库，删除图片
            boolean result = this.removeById(pictureId);
            System.out.println(result);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 删除图片释放对应的额度
            Long spaceId = oldPicture.getSpaceId();
            /** 如果空间id存在就是私人空间，必须释放额度 */
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 删除对象存储中的图片
        this.clearPictureFile(oldPicture);
    }

    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 获取图片url
        String pictureUrl = oldPicture.getUrl();
        // 判断图片是否被多条记录使用
        //查询数据库找
        long count = this.lambdaQuery().eq(Picture::getUrl, pictureUrl).count();
        if (count > 1) return;  //如果多条记录使用图片，不清理
        // 默认公用图库，如果spaceId存在，则改为space
        String preFix = "public";
        Long spaceId = oldPicture.getSpaceId();

        // 判断空间id是否存在，如果不存在为公共空间
        if (spaceId != null) {
            // 存在看是否合法
            if (spaceId > -1) {
                preFix = "space";
            }
        }

        // 清理网页展示图片
        // 由于数据库中是包含主机名的绝对地址，因此转为相对地址
        String rePicUrl = pictureUrl.substring(pictureUrl.indexOf(preFix));
        cosManager.deleteObject(rePicUrl); // 转为相对地址后是webp格式图片，url属性存储的是webp
        //清理缩略图，(如果存在的话）
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            String reThumbanailUrl = thumbnailUrl.substring(pictureUrl.indexOf(preFix));
            cosManager.deleteObject(reThumbanailUrl);
        }
        // 删除原图数据(如果存在的话）
        String baseUrl = oldPicture.getBaseUrl();
        if (StrUtil.isNotBlank(baseUrl)) {
            String reBaseUrl = baseUrl.substring(pictureUrl.indexOf(preFix));
            cosManager.deleteObject(reBaseUrl);
        }
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        //如果空间id不存在则为公共空间，仅管理员或创建用户可操作
        if (spaceId == null) {
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 如果空间id存在则只有创建用户可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1.校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2.校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "对应空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有访问空间权限");
        }
        // 查询空间下所有图片（必须有主色调
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，返回空
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转换为Color对象
        Color targetColor = Color.decode(picColor);
        // 计算相似度并排序
        List<Picture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    //没有主色调的图片放到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 数值越大越相似，排序默认升序，因此取负号
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                .limit(12) // 取前十二个
                .collect(Collectors.toList());

        //转换为PictureVO类并返回
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        /** 获取数据 */
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        String nameRule = pictureEditByBatchRequest.getNameRule();

        /** 1. 校验参数 */
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR, "图片信息不存在");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");
        /** 2. 校验空间权限 */
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限~");
            }
        }
        /** 3. 查询制定字段 */
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();

        if (pictureList.isEmpty()) {
            return;
        }
        /** 4. 更新分类和标签 */
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        fillPictureWithNameRule(pictureList, nameRule);
        /** 5. 批量更新 */
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        // 根据id获取图片，并利用Optional.ofNullable判空
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 校验权限
//        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        // 设置输入图片的url，用显示的webp格式的
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtils.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    /**
     * 批量按序号填充图片名
     *
     * @param pictureList 图片列表
     * @param nameRule    图片名前缀
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        // 序号从1开始
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }
}




